package com.jiaquyun.jcyx.main

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.lifecycle.Observer
import androidx.viewpager.widget.ViewPager
import com.blankj.utilcode.util.*
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayout
import com.jiaquyun.jcyx.R
import com.jiaquyun.jcyx.app.JCApplication
import com.jiaquyun.jcyx.entity.Cat
import com.jiaquyun.jcyx.entity.GoodsActivity
import com.jiaquyun.jcyx.entity.HomeEntity
import com.jiaquyun.jcyx.entity.UserShops
import com.jiaquyun.jcyx.main.goods.GoodsActiveActivity
import com.jiaquyun.jcyx.main.goods.GoodsHomeFragment
import com.jiaquyun.jcyx.main.goods.GoodsScreenActivity
import com.jiaquyun.jcyx.main.goods.GoodsSearchActivity
import com.jiaquyun.jcyx.main.adapter.HomeBannerAdapter
import com.jiaquyun.jcyx.main.adapter.HomeCategoryAdapter
import com.jiaquyun.jcyx.main.adapter.HomeOnePriceAdapter
import com.jiaquyun.jcyx.main.adapter.HomeSeckillAdapter
import com.jiaquyun.jcyx.jetpack.mode.HomeViewModel
import com.jiaquyun.jcyx.main.mine.MineShopsActivity
import com.module.lemlin.custom.GridSpacingItemDecoration
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.image.loadCenterImage
import com.module.lemlin.owner.OwnerViewModeFragment
import com.youth.banner.Banner
import com.youth.banner.indicator.RectangleIndicator
import kotlinx.android.synthetic.main.fragment_main_home.*
import kotlinx.android.synthetic.main.include_home_bar.*
import kotlinx.android.synthetic.main.include_home_heads.*
import kotlinx.android.synthetic.main.item_tab_home.view.*
import java.lang.StringBuilder


class MainHomeFragment : OwnerViewModeFragment<HomeViewModel>(),
    AppBarLayout.OnOffsetChangedListener {

    private val homeBannerAdapter: HomeBannerAdapter = HomeBannerAdapter()
    private val homeCategoryAdapter: HomeCategoryAdapter = HomeCategoryAdapter()
    private val homeSeckillAdapter: HomeSeckillAdapter = HomeSeckillAdapter()
    private val homeOnePriceAdapter: HomeOnePriceAdapter = HomeOnePriceAdapter()

    override val layoutResId: Int
        get() = R.layout.fragment_main_home

    override fun viewModel(): HomeViewModel =
        createViewModel()

    override fun initView() {
        //为Toolbar添加状态栏高度
        BarUtils.addMarginTopEqualStatusBarHeight(toolbarHome)
        BarUtils.addMarginTopEqualStatusBarHeight(includeHomeBar)
        //为AppBar设置滑动监听
        appBarHome.addOnOffsetChangedListener(this)


        //为RecyclerView设内边距
        includeHomeHeads.setPadding(
            ConvertUtils.dp2px(0f), (ConvertUtils.dp2px(75f) + BarUtils.getStatusBarHeight()),
            ConvertUtils.dp2px(0f), ConvertUtils.dp2px(0f)
        )

        //初始轮播视图
//        vpHomeBanner.apply {
//            indicator = RectangleIndicator(context)
//            setIntercept(false)
//        }.setOrientation(Banner.HORIZONTAL).setUserInputEnabled(true)
//            .adapter = homeBannerAdapter

        //初始化分类视图
        rvHomeCategory.apply {
            val decoration = GridSpacingItemDecoration(
                spanCount = 5, spacing = ConvertUtils.dp2px((13f))
            )
            addItemDecoration(decoration)
        }.adapter = homeCategoryAdapter

        homeCategoryAdapter.setOnItemClickListener { _, _, position ->
            val cateEntity: Cat = homeCategoryAdapter.getItem(position)
            GoodsScreenActivity.open(requireActivity(), cateEntity)
        }

        //初始化整点秒杀视图
        rvHomeSeckillBody.adapter = homeSeckillAdapter

        //初始化一口价物品视图
        rvHomeOnePrice.adapter = homeOnePriceAdapter

        tlHomeBody.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) = Unit

            override fun onTabUnselected(tab: TabLayout.Tab?) = Unit

            override fun onTabSelected(tab: TabLayout.Tab?) {
                vpHomeBody.currentItem = tab?.position ?: 0
            }
        })

        vpHomeBody.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) = Unit

            override fun onPageScrolled(
                position: Int, positionOffset: Float, positionOffsetPixels: Int
            ) = Unit

            override fun onPageSelected(position: Int) {
                tlHomeBody.getTabAt(position)?.select()
            }
        })

        tvHomeMore.setOnClickListener {
//            GoodsActiveActivity.open(requireActivity())
        }

        flHomeSearch.setOnClickListener {
            GoodsSearchActivity.open(requireActivity())
        }


        llHomeBarShops.setOnClickListener {
            MineShopsActivity.open()
        }

        if (JCApplication.userShops == null) {
            MineShopsActivity.open()
        } else {
            tvHomeLocal.text = JCApplication.userShops?.shop_name
        }
        //为轮播视图添加数据
        vpHomeBanner.apply {
            indicator = RectangleIndicator(context)
            setIntercept(false)
        }.setOrientation(Banner.HORIZONTAL).setUserInputEnabled(true)
            .adapter = homeBannerAdapter
    }


    override fun initData() {
        viewModel.indexAndGoodsList()
    }

    override fun initViewMode() {
        viewModel.homeLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.SUCCESS) {
                response.data?.data?.let {
                    fillData(it)
                }
            } else if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
        })
    }

    override fun onResume() {
        super.onResume()
        vpHomeBanner.start()
    }

    override fun onPause() {
        super.onPause()
        vpHomeBanner.stop()
    }

    override fun onDestroy() {
        super.onDestroy()
        //vpHomeBanner.destroy()
    }

    private fun fillData(homeEntity: HomeEntity) {

        //为轮播视图添加数据
        homeBannerAdapter.apply {
            setDatas(homeEntity.banner)
        }

        vpHomeBanner.setOnBannerListener { data, _ ->
            if (data !is com.jiaquyun.jcyx.entity.Banner) {
                return@setOnBannerListener
            }
            val goods = GoodsActiveActivity.GoodsActiveValue(
                data.params.toInt(), data.title, data.image
            )
            GoodsActiveActivity.open(requireActivity(), goods)
        }

        //为分类视图添加数据
        homeCategoryAdapter.setNewInstance(homeEntity.cat)

        //为胶囊视图添加数据
        homeEntity.capsule?.let {
            ivHomeCapsule.loadCenterImage(it.image)
        }

        ivHomeCapsule.setOnClickListener {
            val capsule = homeEntity.capsule
                ?:return@setOnClickListener
            val goods = GoodsActiveActivity.GoodsActiveValue(
                if (capsule.params.isNullOrEmpty()) 86 else capsule.params.toInt(), capsule.title, capsule.image
            )
            GoodsActiveActivity.open(requireActivity(), goods)
        }

        //为一口价视图添加数据
        clHomeOnePriceView.visibility =
            if (homeEntity.goodsList.size == 0) View.GONE else View.VISIBLE
        homeOnePriceAdapter.setNewInstance(homeEntity.goodsList)

        //为整点秒杀添加数据
        clHomeSeckill.visibility =
            if (homeEntity.seckill?.seckill.isNullOrEmpty())
                View.GONE else View.VISIBLE
        tvHomeSeckillTime.text = StringBuilder().append(homeEntity.seckill?.start_time)
            .append(":00场")
        val seckillList = homeEntity.seckill?.seckill
        if (!seckillList.isNullOrEmpty()) homeSeckillAdapter.setNewInstance(
            if (seckillList.size > 3) {
                seckillList.take(3).toMutableList()
            } else seckillList
        )

        tlHomeBody.apply {
            for ((index: Int, item: GoodsActivity) in homeEntity.goods_activity.withIndex())
                addTab(newTab().apply {
                    val view: View = LayoutInflater.from(requireContext())
                        .inflate(R.layout.item_tab_home, null)
                    view.text_tab_home_name.text = item.title
                    view.text_tab_home_sub.text = item.subtitle
                    customView = view
                    tag = index
                })
        }

        val size = homeEntity.goods_activity.size

        vpHomeBody.adapter = object : FragmentStatePagerAdapter(
            childFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        ) {
            override fun getItem(position: Int): Fragment =
                GoodsHomeFragment.newInstance(if (size == 0) null else homeEntity.goods_activity[position])

            override fun getCount(): Int = if (size == 0) 1 else size

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {}
        }

    }

    public var alphaStatus: Int = 0

    //搜索布局展开时顶部距离
    private val searchMaxTopMargin: Float =
        ConvertUtils.dp2px(45f).toFloat()

    //搜索布局关闭时顶部距离
    private val searchMinTopMargin: Float =
        ConvertUtils.dp2px(6.5f).toFloat()

    //搜索布局展开时的宽度
    private val searchMaxWidth: Float =
        (ScreenUtils.getScreenWidth() - ConvertUtils.dp2px(26f)).toFloat()

    //搜索布局关闭时的宽度
    private val searchMinWidth: Float =
        (ScreenUtils.getScreenWidth() - ConvertUtils.dp2px(55f)).toFloat()
    private val alphaMaxHeight: Float =
        ConvertUtils.dp2px(10f).toFloat()

    override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {


        if (verticalOffset * -1 == appBarHome.totalScrollRange) {
            tlHomeBody.setBackgroundResource(R.color.colorWhite)
        } else {
            tlHomeBody.setBackgroundResource(R.color.transparent)
        }

        val offset: Float = verticalOffset * -0.65f

        var searchNewTopMargin: Float = searchMaxTopMargin - (offset * 1.5f)
        var searchNewWidth: Float = searchMaxWidth - (offset * 1.15f)
        val alphaNewHeight: Float = alphaMaxHeight - (offset * 0.5f)
        //处理布局的边界问题
        if (searchNewTopMargin < searchMinTopMargin) {
            searchNewTopMargin = searchMinTopMargin
        }
        if (searchNewWidth < searchMinWidth) {
            searchNewWidth = searchMinWidth
        }

        var alpha1: Float = (255 * alphaNewHeight / alphaMaxHeight)
        if (alpha1 < 0)
            alpha1 = 0f
        tvHomeLocal.setTextColor(
            Color.argb(alpha1.toInt(), alpha1.toInt(), alpha1.toInt(), alpha1.toInt())
        )
        ivHomeLocalNext.setColorFilter(
            Color.argb(alpha1.toInt(), alpha1.toInt(), alpha1.toInt(), alpha1.toInt())
        )
        ivHomeScan.setColorFilter(
            Color.argb(alpha1.toInt(), alpha1.toInt(), alpha1.toInt(), alpha1.toInt())
        )
        ivHomeMsg.setColorFilter(
            Color.argb(alpha1.toInt(), alpha1.toInt(), alpha1.toInt(), alpha1.toInt())
        )

        var alpha2: Float =
            255 * (alphaMaxHeight - alphaNewHeight) / alphaMaxHeight
        if (alpha2 > 255)
            alpha2 = 255f
        ivHomeLocal.setColorFilter(
            Color.argb(alpha2.toInt(), 0, 0, 0)
        )
        clHomeSearch.setBackgroundColor(
            Color.argb(alpha2.toInt(), 255, 255, 255)
        )
        flHomeSearch.setBackgroundResource(
            if (alpha2 > 150) R.drawable.bg_radius_20dp_milky else R.drawable.bg_radius_20dp_white
        )
        BarUtils.setStatusBarColor(
            requireActivity(), Color.argb(alpha2.toInt(), 255, 255, 255)
        )
        BarUtils.setStatusBarLightMode(
            requireActivity(), alpha2 > 180
        )
        alphaStatus = alpha2.toInt()

        flHomeSearch.layoutParams =
            (flHomeSearch.layoutParams as ViewGroup.MarginLayoutParams).apply {
                topMargin = searchNewTopMargin.toInt()
                width = searchNewWidth.toInt()
            }
    }


    companion object {
        fun newInstance(): MainHomeFragment {
            return MainHomeFragment()
        }
    }

//    override fun onEventMainThread(any: Any) {
//        if (any is UserShops) {
//            initData()
//            tvHomeLocal.text = any.shop_name
//        }
//    }
}